using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace Autenticazione
{
	public class DB
	{
		private string strConn = string.Empty;
		private SqlConnection Conn
		{
			get
			{
				if (string.IsNullOrEmpty(this.strConn))
				{
					return null;
				}
				return new SqlConnection(this.strConn);
			}
		}
		public DB()
		{
			this.strConn = ConfigurationManager.AppSettings["SqlConnectionString"];
		}
		public DataTable GetTable(string strSQL)
		{
			DataTable tblCoach = new DataTable();
			SqlConnection conn = this.Conn;
			try
			{
				conn.Open();
				SqlDataAdapter ad = new SqlDataAdapter(strSQL, conn);
				ad.Fill(tblCoach);
			}
			catch (SqlException exc)
			{
				throw new Exception(exc.Message);
			}
			finally
			{
				conn.Close();
			}
			return tblCoach;
		}
		public SqlDataReader Reader(string strSQL)
		{
			SqlConnection conn = this.Conn;
			SqlDataReader reader = null;
			if (conn == null)
			{
				return null;
			}
			try
			{
				conn.Open();
				SqlCommand comm = new SqlCommand(strSQL, conn);
				reader = comm.ExecuteReader(CommandBehavior.CloseConnection);
			}
			catch (SqlException exc)
			{
				conn.Close();
				throw new Exception(exc.Message);
			}
			return reader;
		}
		public void CloseConnection()
		{
			SqlConnection conn = this.Conn;
			conn.Close();
		}
		public bool ExecuteNonQuery(string strSQL)
		{
			bool executed = true;
			SqlConnection conn = this.Conn;
			if (conn == null)
			{
				return false;
			}
			try
			{
				conn.Open();
				SqlCommand comm = new SqlCommand(strSQL, conn);
				comm.ExecuteNonQuery();
			}
			catch (SqlException exc)
			{
				executed = false;
				throw new Exception(exc.Message);
			}
			finally
			{
				conn.Close();
			}
			return executed;
		}
		public int ExecuteScalar(string strSQL)
		{
			SqlConnection conn = this.Conn;
			int i = 0;
			if (conn == null)
			{
				return i;
			}
			try
			{
				conn.Open();
				SqlCommand comm = new SqlCommand(strSQL, conn);
				i = (int)comm.ExecuteScalar();
			}
			catch (SqlException exc)
			{
				throw new Exception(exc.Message);
			}
			finally
			{
				conn.Close();
			}
			return i;
		}
	}
}
